<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class WeixinApi extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('FollowModel');
    }

    public function run() {
        $this->ci_wechat->valid();
        $type = $this->ci_wechat->getRev()->getRevType();
        $openid = $this->ci_wechat->getRevFrom();
        switch ($type) {
            case 'text':
                $this->ci_wechat->text('hello,spq.')->reply();
                exit;
                break;
            case 'event':
                $info = $this->ci_wechat->getRevEvent();
                if (isset($info['event'])) {

                    switch ($info['event']) {
                        case 'subscribe':
                            $userInfo = $this->ci_wechat->getUserinfo($openid);
                            $query = array(
                                'openid' => $userInfo['openid'],
                                'nickname' => $userInfo['nickname'],
                                'sex' => $userInfo['sex'],
                                'language' => $userInfo['language'],
                                'city' => $userInfo['city'],
                                'province' => $userInfo['province'],
                                'country' => $userInfo['country'],
                                'headimgurl' => $userInfo['headimgurl'],
                                'subscribe_time' => $userInfo['subscribe_time'],
                            );

                            $this->FollowModel->initFollow($query);

                            $this->ci_wechat->text('欢迎.')->reply();

                            break;
                        case 'unsubscribe':
                            $this->FollowModel->unSubscribe($openid);
                            break;
                        default:
                            break;
                    }
                }
                exit;
                break;
            default:
                break;
        }
    }

    public function menu() {
        //设置菜单
        $newmenu = array(
            "button" =>
            array(
                array('type' => 'view', 'name' => '点我领券', 'url' => 'http://benefit.lovchun.com/benefit/index'),
                array('type' => 'view', 'name' => '测试', 'url' => 'http://benefit.lovchun.com/benefit/test'),
            )
        );
        $result = $this->ci_wechat->createMenu($newmenu);
    }

}
